<template>
  <section>
    <el-row>
      <!--搜索、创建行-->
      <el-col :span="20">
        <el-form :inline="true" size="mini" ref="form">
          <el-form-item label="医院：">
            <!--医院列表-选择-->
            <el-select v-model="selHospital" placeholder="请选择">
              <el-option v-for="hospital in hospitals" :key="hospital.id" :label="hospital.name"
                         :value="hospital.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!--时间选择-->
            <el-date-picker v-model="selWeekStart" type="week" format="yyyy 第 WW 周 MM 月 dd 日" placeholder="选择周">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="showCreateSchedule">
              <icon name="plus"></icon>
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>

      <el-table :data="scheduleList" border style="width: 100%">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column label="周次" prop="title" >
        </el-table-column>
        <el-table-column label="开始日期" prop="begin" >
        </el-table-column>
        <el-table-column label="结束日期" prop="finish" >
        </el-table-column>
        <!--<el-table-column label="可用" width="70">
          <template slot-scope="scope">
            <div style="text-align: center">
              <icon name="check" v-if="scope.row.isEnable" style="color: darkgreen"></icon>
              <icon name="ban" v-else style="color: red;"></icon>
            </div>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button :type="scope.row.edit?'success':'primary'" @click='confirm(scope)' size="small" icon="edit">{{scope.row.edit?'完成':'编辑'}}</el-button>
            <el-button @click='del(scope)' size="small" >DEL</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-row>
    <el-row>
      <el-table   :data="tableDatas" style="width: 100%">
        <el-table-column>
          <el-table-column prop="hospitalName" label="医院">
          </el-table-column>
          <el-table-column prop="departmentName" label="科室">
          </el-table-column>
        </el-table-column>
        <el-table-column v-for="(date,i1) in selWeek" :key="date.text" :label="date.text">
          <el-table-column :label="date.day">
            <el-table-column v-for="(ban,i2) in date.bans" :key="ban" :label="ban">
              <template slot-scope="scope">
                <div @click="showAddDialog(scope.row,i1,i2)"  style="border: 0px solid crimson; min-height: 50px;cursor:pointer">
                  <div v-if="scope.row.repertories[i1*2+i2].length>0">
                    <div v-for="(b,i3) in scope.row.repertories[i1*2+i2]" class="item-box">
                      <div class="icon" @click.stop="remove(b.id)">
                        <icon name="times" width="16" height="16"></icon>
                      </div>
                      <span>{{b.name}}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>
      <el-row>
        <el-button type="success" icon="el-icon-check" circle style="margin-top: 20px" @click="saveScheduleWeek"></el-button>
      </el-row>
    </el-row>

    <el-dialog title="增加新一周排班" :visible.sync="showCreateSchedule" width="480px">
      <el-form :inline="true" size="mini" ref="form">
        <el-form-item label="医院：">
          <!--医院列表-选择-->
          <el-select v-model="selHospital" placeholder="请选择">
            <el-option v-for="hospital in hospitals" :key="hospital.id" :label="hospital.name" :value="hospital.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <!--时间选择-->
          <el-date-picker v-model="selWeekStart" type="week" format="yyyy 第 WW 周 MM 月 dd 日" placeholder="选择周">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDoctor">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="坐诊安排" :visible.sync="showDialog" width="480px">
      <el-form size="small" style="padding:0 40px;margin:0 auto;" label-width="80px">
        <el-form-item label="坐诊医生:">
          <el-select v-model="selDocForm.docId" placeholder="请选择医生">
            <el-option v-for="doctor in doctors" :label="doctor.doctor.name" :value="doctor.doctor.id" :key="doctor.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预  约  量:">
          <el-input v-model="selDocForm.total" style="width:120px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDoctor">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </section>
</template>

<script>
  import {mapGetters, mapActions, mapMutations} from 'vuex';
  import DateUtils from '@/common/DateUtils'

  export default {
    name: "schedule",
    data() {
      return {
        showDialog:false,
        showCreateSchedule:false,
        hospitals: [],
        departments: [],
        selHospital: null,
        selWeekStart: null,
        scheduleList: null,
        selWeek: [],
        doctors:[],
        pos:null,
        selDocForm:{
          departmentId:null,
          date:null,
          time:null,
          docId:null,
          total:20
        },
        title:null
      }
    },
    created() {
      this.loadHospitalList()
      //加载医生列表
      this.getCustomerList(5)
    },
    watch: {
      selWeekStart(nv, ov) {
        //制作新的 weeks
        this.title = DateUtils.getWeekNumber(nv)
        this.selWeek.splice(0, this.selWeek.length)
        for (let i = -1; i < 6; i++) {
          let sec = DateUtils.addDays(nv, i)
          let day = DateUtils.getDay(sec)
          let tmp = {text: DateUtils.format(sec, 'yyyy-MM-dd'), day, bans: ['上午', '下午'], index: i}
          this.selWeek.push(tmp)
        }
        //加载数据
        // if (this.selHospital && this.selWeekStart) {
        //   this.getScheduleList()
        // }
      },
      selHospital(nv, ov) {
        if (nv) {
          this.getDepartments(nv)
          this.loadScheduleList(nv)
        }
        //加载医院下所有排班
        // if (this.selHospital && this.selWeekStart) {
        //   this.getScheduleList()
        // }
      }
    },
    computed: {
      tableDatas() {//------------------------计算显示的排班
        if (this.scheduleList) {
          console.log(this.scheduleList)
          let rets = []
          this.departments.forEach(d => {
            let data = {
              hospitalName: d.hospitalId,
              departmentId: d.id,
              departmentName: d.name,
              repertories: [[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
            }
            rets.push(data)
          })
          this.scheduleList.forEach(s => {
            //查找科室
            let department = this.departments.find(d => d.id === s.department.id)
            if (department) {
              let dIndex = rets.findIndex(i => i.departmentId === department.id)
              let theObj = rets[dIndex]
              //计算 14个是阶段
              let day = DateUtils.parseDate(s.date).getDay()
              let time = s.time === '1' ? 0 : 1
              let colIndex = day * 2 + time
              let theRep = theObj.repertories[colIndex]
              //加医生了
              theRep.push({id: s.id, name: s.doctorName,total:s.total})
            }
          })
          return rets
        } else
          return null
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      confirm(scope){//确认/编辑排班
        if(this.scheduleList[scope.$index].achieve){
          console.log('true'+this.scheduleList[scope.$index].achieve)
          this.$message('该排班已确认完成，不能编辑')
        }else {
          console.log('false'+this.scheduleList[scope.$index].achieve)
        }
      },
      saveScheduleWeek(){
        //确定不再修改排班了
      },
      showCreateSchedule(){//-------------------显示新建排班的对话框
        this.showCreateSchedule = true
        console.log(this.selHospital)
        let tmp = this.scheduleList.find(i => i.title === this.title)
        if(tmp){

        }else {
          this.fetch({name:"createSchedule",data:{title:this.title,hospitalId:this.selHospital,begin:this.selWeek[0].text,finish:this.selWeek[this.selWeek.length-1].text}})
            .then((res)=>{
              if(res.errCode){
                this.$message({type:'info',message:res.errMsg})
              }else{
                console.log(res)
              }
            })
            .catch((err)=>{
              console.log(err)
              this.$message({type:'error',message:"服务器错误"})
            })
        }
      },
      getCustomerList(id){//-----------通过用户组id获取该用户组下所有用户（获取医生列表）
        this.fetch({name:"getCustomerList",data:{groupId:id}})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              // console.log(res)
              for(let i=0;i<res.length;i++){
                let tmp = res[i]
                this.doctors.push({doctor:tmp,amount:''})
                // console.log(this.doctors)
              }
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      loadScheduleList(id) {//--------------加载该医院下的所有排班
        this.fetch({name: "getScheduleList",data:{hospitalId:id}})
          .then((res) => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              console.log(res)
              this.scheduleList = res
            }
          })
          .catch((err) => {
            console.log(err)
            this.$message({type: 'error', message: "服务器错误"})
          })
      },
      /**
       * 删除一个排班项
       * @param sid 排班的id 用于删除数据库的
       */
      remove(sid){//---------------------------删除排班项
        this.fetch({name:'delSecheduleItem',data:{id:sid}})
          .then(res=>{
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              // console.log(res)
              //删除界面里的元素
              let index = this.scheduleList.findIndex(s=> s.id === sid )
              if(index>=0)
                this.scheduleList.splice(index,1)
            }
          }).catch(err=>{
          console.log(err)
          this.$message({type: 'error', message: err.errMsg})
        })
      },
      showAddDialog(row,date,time){//--------------------显示编辑排班框
        this.selDocForm.departmentId = row.departmentId
        // console.log(ii)//0~6,周日~周一
        // console.log(i2)//0~1,上午，下午
        this.pos = date*2+time
        console.log(this.pos)
        this.selDocForm.departmentId = row.departmentId
        this.selDocForm.date = this.selWeek[date].text
        if(time === 0){
          this.selDocForm.time = '1'
        }else if(time === 1){
          this.selDocForm.time = '2'
        }
        this.showDialog = true
      },
      addDoctor(){//----------------增加排班项
        let data ={date:this.selDocForm.date,
          time:this.selDocForm.time,
          departmentId:this.selDocForm.departmentId,
          doctorId:this.selDocForm.docId,
          scheduleId:this.selDocForm.total}
        this.fetch({name:"creatSecheduleItem",data:data})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              let index = this.departments.findIndex(i => i.id === res.department.id)
              this.tableDatas[index].repertories[this.pos].push({id:res.id,name:res.doctorName,total:res.total})
              this.showDialog = false
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      getDepartments(hospitalId) {//-------------通过医院获取科室
        this.fetch({name: "getDepartmentByHospital", data: {hospitalId}})
          .then(res => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              this.departments = res
              console.log(this.departments)
            }
          }).catch(err => {
          console.log(err)
          this.$message({type: 'error', message: err.errMsg})
        })
      },
      loadHospitalList() {//----------------加载医院列表
        this.fetch({name: "getHospitalList"})
          .then((res) => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              // console.log(res)
              this.hospitals = res
            }
          })
          .catch((err) => {
            console.log(err)
            this.$message({type: 'error', message: "服务器错误"})
          })
      },
    }
  }
</script>

<style lang="scss">

  .item-box{
    position: relative;
    line-height:24px;
    border:0px solid #777;
    .icon{
      width:16px;
      height:16px;
      color: red;
      top:3px;
      right: -10px;
      position: absolute;
      display: none;
    }
    span{
      height:24px;
      line-height:24px;
    }
    &:hover{
      .icon{
        display: inline;
      }
    }
  }

</style>
